import {CheckOutlined, InboxOutlined, UndoOutlined} from '@ant-design/icons';
import {
  Layout,
  message,
  Form,
  Button,
  Space,
  Upload,
  UploadProps,
  Row,
  Modal,
  Input,
  Popconfirm,
  Select,
  Progress,
  TreeSelect,
} from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import MultiImgUpload from '@/components/multiImgUpload';
import '@/assets/css/index.less';
import ProForm, { ProFormText, ProFormSelect } from '@ant-design/pro-form';
import { useForm } from 'antd/es/form/Form';
import {
  getPhotoById,
  getPhotoCategoryList,
  releasePhoto,
  updatePhoto,
  uploadList,
} from '@/services/pictureManager';
import axios from 'axios';
import formatDate from '@/utils/formatDate';
import { useLocation } from 'umi';
import { getCategoryList } from '@/services/category';
import { response } from 'express';
import {history} from "@@/core/history";
import {useModel} from "@@/plugin-model/useModel";
import {BASE_URL} from "../../../../proxyConfig";

const MNTPrefix = BASE_URL;

const { Header, Content, Footer } = Layout;
const { Dragger } = Upload;
const { TextArea } = Input;
const generatTreeData = (data) => {
  data.map((item, index) => {
    data[index].value = item.id;
    data[index].title = item.name;
    if (item.children && item.children.length > 0) {
      generatTreeData(item.children);
    }
  });
  return data;
};
const PicturenEdit: React.FC = () => {
  const location = useLocation();
  const [fileList, setFileList] = useState([]);
  const [currentFormValues, setCurrentFormValues] = useState(location.state?.formValues);
  const [fileListLength, setFileListLength] = useState(0);
  const [fileLoading, setFileLoading] = useState(true);
  const [fileResponse, setResponse] = useState([]);
  const [categoryTreeData, setCategoryTreeData] = useState([]);
  const [previewOpen, setPreviewOpen] = useState(false);
  const [previewImage, setPreviewImage] = useState('');
  const [previewTitle, setPreviewTitle] = useState('');
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const onSubmit = async (values) => {
    let fileListArray = [];
    let tmp = [];
    const date = new Date();
    //图片为空
    if (fileList.length === 0) {
      message.error('图片为空，请上传图片！');
      return;
    } else {
      // fileListArray = fileList;
      fileList.map((item) => {
        if (item.response) fileListArray.push(item.response.data.data[0]);
        else fileListArray.push(JSON.parse(JSON.stringify(item).replace('name', 'fileName')));
      });
    }

    // else if(values.fileList == undefined){
    //     // 不增加新的图片
    //     fileList.map( item => {
    //         const _item = JSON.parse(JSON.stringify(item).replace('name', 'fileName'));
    //         fileListArray.push(_item);
    //     })

    // }else if(values.fileList != undefined){
    //     //增加新的图片或者将原有图片都换成新的图片
    //     values.fileList && values.fileList.fileList.map(item => {
    //         if(item.response != undefined){
    //             fileListArray.push(item.response.data.data[0]);
    //         }else{
    //             const _item = JSON.parse(JSON.stringify(item).replace('name', 'fileName'));
    //             fileListArray.push(_item);
    //         }

    //     })
    // }
    tmp = {
      author:currentUser.name,
      ...values,
      fileList: fileListArray,
      id: currentFormValues.id,
      releaseTime:
        date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() + ' ' + '00:00:00',
    };

    try {
      const res = await updatePhoto(tmp);
      message.success('上传成功');
      window.history.back(-1)
/*      history.push({
        pathname:'/webDesign/imageCenter/index'
      });

      window.location.href = window.location.href.replace(/webDesign/, '/webDesign/imageEdit/index');*/
    } catch (error) {
      message.error(error.response.data.data);
    }
  };
  const handleCancel = () => setPreviewOpen(false);

  const transResponseToFilelist = (res) => {
    let fileList = [];
    res.map((item) => {
      item['url'] = MNTPrefix + item['src'];
      //fileList里面改成name为了给Upload的fileList用
      let _item = JSON.parse(JSON.stringify(item).replace('fileName', 'name'));

      fileList.push(_item);
    });
    return fileList;
  };
  const getPictureByID = async () => {
    const res = await getPhotoById({
      id: currentFormValues.id,
    });

    if (res.code == 0) {
      setFileLoading(false);
      const fileListnew = transResponseToFilelist(res.data.fileList);
      setFileList(fileListnew);
      setFileListLength(fileListnew.length);
    }
  };

  useEffect(() => {
    getPictureByID();
  }, [currentFormValues]);

  const getCategory = () => {
    const params = {
      type: 'photo',
    };
    //获取组list
    getCategoryList(params).then(async (res) => {
      const data = generatTreeData(res.data);
      setCategoryTreeData(data);
    });
  };
  useEffect(() => {
    getCategory();
  }, []);

  const [form] = useForm();
  const [progress, setProgress] = useState(0);
  const formLayout = {
    labelCol: {
      span: 6,
    },
    wrapperCol: {
      span: 14,
    },
  };
  // const onRemoveFile = (file) => {
  //     console.log(file);
  //     fileList.splice(fileList.findIndex(item=> item.uid === file.uid), 1);
  //     setFileList(fileList);
  //     setFileListLength(fileList.length)
  //     fileResponse.splice(fileResponse.findIndex(item => {
  //         if(item.fileName.indexOf('.') != -1)
  //             return item.fileName === file.name.split('.')[0]
  //         else
  //             return item.fileName === file.name
  //         }, 1));
  //     setResponse(fileResponse);
  // }
  const validatorFuncion = (rule, value, callback) => {
    if (fileList.length != 0) {
      callback();
    } else if (!value) {
      callback('请上传图片！');
    }
  };
  return (
    <PageContainer
      header={{
        title: '编辑图片',
        breadcrumb: {
          items: [
            {
              // path: '',
              title: '图片中心',
            },
            {
              title: '编辑图片',
            },
          ],
        },
      }}
    >
      {/* <Header style={{ padding: 0, background: "rgba(0,0,0,0)", fontSize: 20 }}>编辑图片</Header> */}

      <ProForm
        form={form}
        layout="horizontal"
        {...formLayout}
        initialValues={currentFormValues || {}}
        onFinish={onSubmit}
        onReset={() => {
          window.history.back();
        }}
        submitter={{
          render: (_, dom) => (
            <div style={{ display: 'flex', justifyContent: 'center' }}>
              <Space>
                {/*{dom}*/}
                {<Button onClick={() => {
                  _.reset()
                }}><UndoOutlined />返回</Button>}
                {<Button type={"primary"} onClick={() => {
                  _.submit()
                }}><CheckOutlined />提交</Button>}

              </Space>
            </div>
          ),
        }}
      >
        <ProFormText
          rules={[
            {
              required: true,
              message: '主题名称必填',
            },
          ]}
          width="md"
          name="theme"
          placeholder="请填写主题名称"
          label="主题名称"
        />
        <Form.Item label="说明" name="description">
          <TextArea
            className=""
            showCount
            maxLength={300}
            // style={{ height: 120, marginBottom: 24, width: 300}}
            // onChange={onChange}
            placeholder="输入备注信息"
          />
        </Form.Item>

        {/* <Form.Item  label="发布时间" name= "releaseTime">
                <DatePicker format={"YYYY-MM-DD"}/>
            </Form.Item> */}

        {/* <ProFormSelect
                rules={[
                    {
                    required: true,
                    message: '图片分类必填',
                    },
                ]}
                width="md"
                label="图片分类"
                // width="60%"
                name="photoCategoryId"
                defaultValue={currentFormValues && currentFormValues.photoCategory}
                // options={[
                //     {label: 1, value:1},
                //     {label: 2, value:2},
                //     {label: 3, value:3}
                // ]}
                placeholder="请选择"
                request={
                    async () => {
                    // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
                    // 如果需要转化参数可以在这里进行修改
                    const msg = await getPhotoCategoryList();
                    let res = []
                    msg.data.photoCategoryList.map(item => {
                        let temp = {};
                        temp['label'] = item.name;
                        temp['value'] = item.id;
                        res.push(temp)

                    })
                    return res;
                    }

                }
                /> */}

        <Form.Item
          rules={[
            {
              required: true,
              message: '图片分类必填',
            },
          ]}
          width="md"
          label="图片分类"
          // width="60%"
          name="photoCategoryId"
          defaultValue={currentFormValues && currentFormValues.photoCategory}
        >
          <TreeSelect treeData={categoryTreeData} placeholder="请选择图片分类" />
        </Form.Item>
{/*        <ProFormText
          rules={[
            {
              required: true,
              message: '发布作者必填',
            },
          ]}
          width="md"
          name="author"
          placeholder="请填写发布作者"
          label="发布作者"
        />*/}
        <ProFormText
          rules={[
            {
              required: true,
              message: '信息来源必填',
            },
          ]}
          width="md"
          name="source"
          placeholder="请填写信息来源"
          label="信息来源"
        />

        <Form.Item
          label="上传图片"
          name="fileList"
          rules={[
            {
              required: true,
              message: '请上传图片',
              validator: validatorFuncion,
            },
          ]}
        >
          <MultiImgUpload
            form={form}
            fileList={fileList}
            setFileList={setFileList}
            url={'/api/v1/photo/uploadList'}
            fileResponse={fileResponse}
            setResponse={setResponse}
          />
        </Form.Item>
        <Modal open={previewOpen} title={previewTitle} footer={null} onCancel={handleCancel}>
          <img
            alt="example"
            style={{
              width: '100%',
            }}
            src={previewImage}
          />
        </Modal>
        <Form.Item label=" " style={{ display: fileLoading ? 'block' : 'none' }}>
          <Button type="primary" loading />
        </Form.Item>
      </ProForm>
    </PageContainer>
  );
};
export default PicturenEdit;
